import yaml from 'js-yaml'
import { EXT_OPT, MENU_OPTIONS, FindProxyForURL } from '/src/constants'

export const getStorage = async (key) => {
  return new Promise((resolve) => chrome.storage.sync.get(key, resolve))
}

export const initOpt = (type) => {
  const opts = type === 'POPUP'
    ? MENU_OPTIONS.filter(op => op.key !== 'new')
    : MENU_OPTIONS.filter(op => op.key !== 'direct' && op.key !== 'system')

  return opts
}

const reg = (exp, ret) => {
    const rule = []

    exp.forEach(it => {
      rule.push(`new RegExp('${it}').test(host)`)
    })

    return `if (${rule.join('||')}) return '${ret}';`
}

const getProxy = async (label) =>  {
  const { opt_ext } = await getStorage(EXT_OPT)
  for (let op in opt_ext) {
      if (opt_ext[op].label === label) {
          const { scheme, host, port } = opt_ext[op].value
          // TODO: scheme
          return `${scheme === 'socks5' ? 'SOCKS5' : 'PROXY'} ${host}:${port}`
      }
  }
}

export const yaml2pac = async (val) => {
  const json = yaml.load(val)
  let str = ''

  for (let i in json) {
    switch(i) {
      case 'direct':
        if (json[i]) str += reg(json[i], 'DIRECT') + '\n'
        break
      case 'system':
        if (json[i]) str += reg(json[i], 'SYSTEM') + '\n'
        break
      default:
        if (json[i]) {
          const proxy = await getProxy(i)
          if (proxy) {
            str += reg(json[i], proxy) + '\n'
          } else {
            console.warn('not find custom proxy config')
          }
        }
    }
  }

  return FindProxyForURL.replace('"RULE";', str)
}